package com.my.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.my.blog.constant.SystemConstants;
import com.my.blog.dao.MenuMapper;
import com.my.blog.domain.entity.Menu;
import com.my.blog.domain.vo.MenuVo;
import com.my.blog.service.IMenuService;
import com.my.blog.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author WH
 * @since 2025-06-05
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public List<String> selectPermsByUserId(Long id) {
        // 如果是管理员，返回所有权限标识
        if (id == 1L) {
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Menu::getMenuType, "C", "F")
                    .eq(Menu::getStatus, SystemConstants.STATUS_NORMAL);
            List<Menu> menus = menuMapper.selectList(queryWrapper);
            List<String> perms = menus.stream().map(Menu::getPerms).collect(Collectors.toList());
            return perms;
        }
        // 否则返回用户所具有的权限标识
        List<String> perms = menuMapper.selectPermsByUserId(id);
        return perms;
    }

    @Override
    public List<MenuVo> selectRouterMenuTreeByUserId(Long userId) {

        List<Menu> menus = null;
        // 判断是否是管理员
        if (userId == 1L) {
            // 所有菜单类型为C或者M的，状态为正常的，未被删除的菜单
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(Menu::getMenuType, "C", "M")
                    .eq(Menu::getStatus, SystemConstants.STATUS_NORMAL)
                    .orderByAsc(Menu::getParentId, Menu::getOrderNum);
            menus = menuMapper.selectList(queryWrapper);
        } else {
            menus = menuMapper.selectRouterMenuByUserId(userId);
        }

        // 将perm值为null的替换为空字符串
        for (Menu menu : menus) {
            if (menu.getPerms() == null) {
                menu.setPerms("");
            }
        }
        // 做数据封装，使用MenuVo
        List<MenuVo> menuVos = BeanCopyUtils.copyList(menus, MenuVo.class);

        // 构建父子菜单，先找一级菜单，再把子菜单设置到一级菜单的children中
        List<MenuVo> menuTree = buildMenuTree(menuVos);
        return menuTree;
    }

    private List<MenuVo> buildMenuTree(List<MenuVo> menuVos) {
        // 先找一级菜单（parentId 为 0L 的菜单）
        List<MenuVo> menuTree = menuVos.stream()
                .filter(menuVo -> menuVo.getParentId().equals(0L))
                // 为一级菜单设置子菜单
                .map(menuVo -> setChildrenList(menuVo, menuVos))
                .collect(Collectors.toList());
        return menuTree;
    }

    private MenuVo setChildrenList(MenuVo parent, List<MenuVo> menuVos) {
        // 从所有菜单中筛选出 parentId 匹配当前父菜单 ID 的子菜单
        List<MenuVo> childrenList = menuVos.stream()
                .filter(menuVo -> menuVo.getParentId().equals(parent.getId()))
                .collect(Collectors.toList());

        // 递归为子菜单设置子菜单（如果有多层嵌套）
        childrenList.forEach(child -> setChildrenList(child, menuVos));

        parent.setChildren(childrenList);
        return parent;
    }
}

